package com.tools.developer.signature;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageParser;
import android.content.pm.Signature;
import android.util.DisplayMetrics;

public class SignatureUtil {

	public static Signature[] getSignatureArray(Context context, String pkgName) {
		PackageManager pm = context.getPackageManager();
		try {
			PackageInfo pi = pm.getPackageInfo(pkgName,
					PackageManager.GET_SIGNATURES);// 必须是GET_SIGNATURES
			return pi.signatures;
		} catch (NameNotFoundException e) {
		}
		return null;

	}

	public static Signature getSignatureFrist(Context context, String pkgName) {
		Signature[] signArray = getSignatureArray(context, pkgName);
		if (signArray.length > 0) {
			Signature sign = signArray[0];
			return sign;
		}

		return null;

	}

	public static X509Certificate getX509Certificate(Signature signature) {
		try {
			CertificateFactory certFactory = CertificateFactory
					.getInstance("X.509");
			X509Certificate cert = (X509Certificate) certFactory
					.generateCertificate(new ByteArrayInputStream(signature
							.toByteArray()));
			return cert;
		} catch (CertificateException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 
	 * @param archiveFilePath
	 * @param flags需设置PackageManager
	 *            .GET_SIGNATURES位，以保证返回证书签名信息
	 * @return
	 */
	public static PackageInfo parsePackage(String archiveFilePath, int flags) {

		PackageParser packageParser = new PackageParser(archiveFilePath);
		DisplayMetrics metrics = new DisplayMetrics();
		metrics.setToDefaults();
		final File sourceFile = new File(archiveFilePath);
		PackageParser.Package pkg = packageParser.parsePackage(sourceFile,
				archiveFilePath, metrics, 0);
		if (pkg == null) {
			return null;
		}

		packageParser.collectCertificates(pkg, 0);
		return null;
//		return PackageParser.generatePackageInfo(pkg, null, flags);
	}
}
